var centerOfUSC = new GLatLng(34.021844, -118.286018);
var HOUSE_IMAGE = "images/home.png";
var map;
var directions;
var homeAddr="";
var homeMarker;
var placeData;
var bounds = new GLatLngBounds();

var houseIcon = new GIcon(G_DEFAULT_ICON);
houseIcon.image = HOUSE_IMAGE;
houseIcon.iconSize = new GSize(32,28);
houseIcon.iconAnchor = new GPoint(16,28);

function addFuclaOverlay() {
  var corner1 = new GLatLng(34.065014, -118.454504);
  var corner2 = new GLatLng(34.078398, -118.434849);
  var ucla_bounds = new GLatLngBounds(corner1, corner2);
  var fucla_image = "images/fucla.png";
  var overlay = new GGroundOverlay(fucla_image,ucla_bounds);
  map.addOverlay(overlay);
}

function updatePlaces(jsonStr) {
  for (i in placeData) {
    placeData[i].removeMarker();
  }
  placeData = eval(jsonStr);
  for (i in placeData) {
    //need all of the following functions to be defined for each place. this is where creating a class called Place or Restaurant would probably have been a better choice...
    placeData[i].addMarker = addMarker;
    placeData[i].showPlaceInfo = showPlaceInfo ;
    placeData[i].setDist = setDist;
    placeData[i].setTime = setTime;
    placeData[i].removeMarker = removeMarker;
    placeData[i].getTravelCost = getTravelCost;
    placeData[i].getTravelCO2 = getTravelCO2;
    placeData[i].getAddress = getAddress;
    //need to actually execute some of them
    if (placeData[i].lat == 0 || placeData[i].lng == 0) //which should never happen, because if it did, it would be eliminated before it got to me. but just in case
    {
      var geocoder = new GClientGeocoder();
      place = placeData[i];
      geocoder.getLatLng(place.getAddress(), function(latLng) {
        place.lat = latLng.lat();
        place.lng = latLng.lng();
      });
    }
    placeData[i].addMarker();
    placeData[i].setDist();
    placeData[i].setTime();
  }
  map.setCenter(bounds.getCenter());
  level = map.getBoundsZoomLevel(bounds);
  map.setZoom(level);
}

function getAddress() {
  return this.address1+", "+this.address2;
}

function getTravelCost() {
  var mpg = getElem("settings_mpg").value;
  var gasCost = getElem("settings_dpg").value;
  return this.dist*gasCost / mpg;
}
function getTravelCO2() {
  var CO2pg = getElem("settings_cpg").value;//how many pounds of CO2 is released per gallon of gas?
  var mpg = getElem("settings_mpg").value;
  return this.dist / mpg * CO2pg;
}

function addMarker() {
  var place = this;
  var address = place.getAddress();
  icon = new GIcon(G_DEFAULT_ICON);
  var cost = place.green.length;
  //icon.image = "images/"+cost+"bucks.png";
  icon.image = "images/dollar"+cost+".png";
  icon.iconSize = new GSize(21, 36);
  icon.iconAnchor = new GPoint(10, 36);
  latLng=new GLatLng(place.lat, place.lng);
  bounds.extend(latLng);
  var newMarker = new GMarker(latLng, icon);
  place.marker = newMarker;
  map.addOverlay(newMarker);
  GEvent.addListener(newMarker, "click", function() {
    place.showPlaceInfo();
    //todo: 'activate' corresponding object in list
  });
}

function removeMarker() {
  map.removeOverlay(this.marker);
}
function showPlaceInfo() {
  var place = this;
  var html = "";
  if (place.website)
  {
    var target = getElem("setting_target");
    html += '<b>Name:</b> <a href="'+place.website+'" target="'+target+'">'+place.name+'</a><br />';
  }
  else
  {
    html += "<b>Name:</b> "+place.name+"<br />";
  }
  if (place.phone != "") html += "<b>Phone: </b>"+place.phone+"<br />";
  if (place.hours != "") html += "<b>Hours: </b>"+place.hours+"<br />";
  if (place.specialties != "") html += "<b>Specialties: </b>"+place.specialties+"<br />";
  html += place.getAddress() + "<br />";
  place.marker.openInfoWindowHtml(html);
  if (homeAddr != "") { //should be controlled so it's always either a valid geocode-able address, or an empty string
    var query = "from: "+homeAddr+" to: "+place.getAddress();
    //place.marker.openInfoWindow("Please wait...");
    GEvent.addListener(directions, "load", function() {
      var place = this;
      //this never shows in the console!!!!!!
    console.log(place);
      var dist = (directions.getDistance().meters / 1609.344);
      var time = directions.getDuration().html; //string, e.g. "about 45 mins"
      var travelCost = place.getTravelCost();
      var emissions = place.getTravelCO2()
      html += "<b>Distance:</b> "+dist.toFixed(2)+" miles <br />";
      html += "<b>Time: </b>"+time+"<br />";
      if (!isNaN(travelCost))
        html += "<b>Gas cost:</b> $"+travelCost.toFixed(2)+"<br />";
      if (!isNaN(emissions))
        html += "<b>CO<sub>2</sub> Emissions:</b> "+emissions.toFixed(2)+" pounds"+"<br />";
      place.marker.openInfoWindowHtml(html);
    });
    directions.load(query);
  }
  else
  {
    html += "<br />To calculate travel data, click on the Settings tab and fill in all the fields.";
    place.marker.openInfoWindowHtml(html);
  }    
}

function setDist() {
  var place = this;
  var query = "from: "+homeAddr+" to: "+place.address;
  directions.load(query);
  var dist;
  GEvent.addListener(directions, "load", function() {
    place.dist = directions.getDistance().meters / 1609.344;
  });
}
function setTime() {
  var place = this;
  var query = "from: "+homeAddr+" to: "+place.getAddress();
  directions.load(query);
  var dist;
  GEvent.addListener(directions, "load", function() {
    place.time = directions.getDuration().html;
  });
}

function initialize() {
  if (GBrowserIsCompatible()) {
  map = new GMap2(document.getElementById("map_canvas"));  
  map.setCenter(new GLatLng(33.930827, -118.0577099), 10);
  var mtCtrl = new GMapTypeControl();
  var ctrlPosn = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,15));
  map.addControl(mtCtrl);// pass stdCtrlPosn as 2nd arg to move to lower right
  map.addControl(new GSmallMapControl());
  directions = new GDirections();
  addFuclaOverlay();
}}

function plotHome(inputStr) {
  if (inputStr=="")
  {
    changeHomeValid();
    if (homeMarker)
      map.removeOverlay(homeMarker);
    homeAddr="";
  }
  else {
    var geocoder = new GClientGeocoder();
    geocoder.getLatLng(inputStr, function(latLng) {
      if (!latLng) {
        changeHomeInvalid();
      }
      else {
        changeHomeValid();
        homeAddr = inputStr;
        if (homeMarker)
          map.removeOverlay(homeMarker);
        homeMarker = new GMarker(latLng, {'icon': houseIcon});
        map.addOverlay(homeMarker);
        map.panTo(latLng);
      }
    });
  }
}

function showInfoById(id) { //gets id # of a restaurant, and calls showPlaceInfo() for that restaurant
  for (i in placeData)
  {
    if (placeData[i].id == id)
      placeData[i].showPlaceInfo();
  }
}

function addressIsValid() {getElem("settings_home_result").value = 'true';}
function addressIsInvalid() {getElem("settings_home_result").value = 'false';}
function addressIsBlank() {addressIsValid();}

